<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\wh\model\Material as MaterialModel;
use app\wh\model\Supplier as SupplierModel;
use app\wh\model\StockType as StockTypeModel;
use app\wh\model\MaterialGoods as MaterialGoodsModel;
use app\wh\model\Stock as StockModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\wh\model\Color as ColorModel;
use form\complexTable\Builder;
use think\Db;
use think\facade\Env;

/**
 * 采购单控制器
 * @package app\admin\controller
 */
class Material extends Admin
{
    public $_type_pid = '';
    public $_type_id = '';
    /**
     * 初始化
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     */
    protected function initialize(){
        parent::initialize();

        $this->_type_pid = input('stock_ptype',cookie('_type_pid'));

        $this->_type_id = input('stock_type',cookie('_type_id'));
        cookie('_type_id',$this->_type_id);

        if(input('stock_ptype') && !input('stock_type')){
            $this->_type_id = '';
            cookie('_type_id',null);
        }

        if($this->_type_id)$this->_type_pid = Db::name('wh_stock_type')->where(['id'=>$this->_type_id])->value('pid');
        elseif(empty($this->_type_pid))$this->_type_pid = StockTypeModel::getTypePidFirst(0,false);
        cookie('_type_pid',$this->_type_pid);

    }
    //首页
    public function index(){

        return $this->fetch();
    }

    /**
     * 获取文档信息并编译
     */
    public function materialFile()
    {

        // 接收附件 ID
        $id = input('param.id');
        // 获取附件 ID 完整路径
        $file = get_file_path($id);
        //$full_path = 'D:/office/phpstudy_pro/WWW/xxy/public/uploads/files/20210611/49dc8272891a2dbdc3396fc055d8017c.xls';
        if(strpos(getcwd(),'public') && strpos($file,'public'))$file = explode('public',$file)[1];
        $full_path = getcwd() . $file;

        $table = [
            'sheet'         =>  '面板订料单',
            'rowStart'      =>  6,
            //'rowEnd'        =>  5,
            'table'         =>  'material_file',
            'fields'        =>  [
                'B'         =>  'type_id_title',
                'D'         =>  'high',
                'F'         =>  'long',
                'G'         =>  'num',
                'H'         =>  'row_area',
                'I'         =>  'number',
                'J'         =>  'material_sn',
            ],
            'group'         =>  [
                'fields'    =>  ['type_id_title'],
                'sum'       =>  ['num','number','row_area']
            ]
        ];
        $sheet_read_arr = [$table];
        $import = plugin_action('Excel/Excel/importarchives', [$full_path,$sheet_read_arr]);

        if(!empty($import['material_file']['lists'])){
            // 接收采购单类型
            $pid = input('param.pid');
            foreach ($import['material_file']['lists'] as &$v){
                //获取采购单类型子ID
                $v['type_id'] = Db::name('wh_stock_type')->where(['pid'=>$pid,'title'=>$v['type_id_title']])->value('id');
                if(empty($v['type_id'])){
                    $add = [
                        'pid'           =>  $pid,
                        'title'         =>  $v['type_id_title'],
                        'sort'          =>  100,
                        'create_time'   =>  time(),
                        'update_time'   =>  time(),
                    ];
                    $v['type_id'] = Db::name('wh_stock_type')->insertGetId($add);
                }
                //获取采购单类型供应商
                if(empty($v['supplier_id_title']))$v['supplier_id_title'] = '无供应商';
                $v['supplier_id'] = Db::name('wh_supplier')->where("find_in_set('$pid',type_pid)")->where(['title'=>$v['supplier_id_title']])->value('id');
                if(empty($v['supplier_id'])){
                    $add = [
                        'type_pid'      =>  $pid,
                        'title'         =>  $v['supplier_id_title'],
                        'title_abb'     =>  $v['supplier_id_title'],
                        'sort'          =>  100,
                        'create_time'   =>  time(),
                        'update_time'   =>  time(),
                    ];
                    $v['supplier_id'] = Db::name('wh_supplier')->insertGetId($add);
                }
                //获取备注，用于采购单编号
                if(strpos($v['material_sn'],'-') && empty($import['material_file']['order'])){
                    $import['material_file']['order']['lists'][] = [
                        'material_sn'   =>  $v['material_sn']
                    ];
                }
            }
        }

        echo json_encode($import['material_file'],JSON_UNESCAPED_UNICODE);exit;

    }
    //新增
    public function add($is_add = true)
    {

        $print = input('print',0);
        $id = input('id');
        $ainp_id = input('ainp_id');
        $order_ids = trim(input('order_ids'),',');
        $not_order_color_ids = trim(input('not_order_color_ids'),',');
        $type_pid = input('type_pid');
        $is_order_color = input('is_order_color',1);//是否按确认颜色的工程来创建采购单 0:不按工程 1:按工程

        if ($this->request->isPost()) {
            $data = input();

            //要校验的字段
            $validate = [
                'type_id'               =>  '请选择物料类别',
                'supplier_id'           =>  '请选择供应商',
                'material_name'         =>  '请填写物料名称',
                'number'                =>  '请填写需求量',
                'model'                 =>  '请填写规格',
            ];
            if(in_array($type_pid,ColorModel::$type_pid_arr)){
                unset($validate['number']);
                unset($validate['model']);
            }
            elseif($type_pid == 4 || $type_pid == 5){
                $validate['quality'] = '请选择材质';
                $validate['lot_sn'] = '请填写批号';
                //$data['status'] = 1;//铝卷跳过审核流程
            }
            /*elseif($type_pid == 5){
                unset($validate['number']);
                unset($validate['supplier_id']);
            }*/
            elseif($type_pid == 6 || $type_pid == 7){
                unset($validate['material_name']);
                //$data['status'] = 1;//铝板跳过审核流程
            }
            $lists = MaterialModel::serialize($data['goods'],0,$validate);
            if(!is_array($lists))$this->error($lists);
            unset($data['goods']);

            if(empty($data['material_sn']))$data['material_sn'] = MaterialModel::getMaterialSn();//采购单编号
            if(empty($data['create_time']))$data['create_time'] = date('Y-m-d H:i:s');
            $data['create_time'] = strtotime($data['create_time']);
            if(!empty($data['address_time']))$data['address_time'] = strtotime($data['address_time']);
            $data['update_time'] = time();
            if(!empty($id)){

                $info = Db::name('wh_material')->where(['id'=>$id])->find();
                if(in_array($type_pid,ColorModel::$type_pid_arr)){

                    //新数据的color_ids
                    $data_order_color_ids = explode(',',$data['order_color_ids']);
                    //原数据的color_ids
                    $info_order_color_ids = explode(',',$info['order_color_ids']);
                    $old_order_color_ids = '';
                    //遍历，筛选出删掉的color_ids，并更新状态
                    foreach ($info_order_color_ids as $cik=>$civ){
                        if(!in_array($civ,$data_order_color_ids))$old_order_color_ids .= ",{$civ}";
                    }

                    if(!empty($data['order_color_ids']))Db::name('wh_order_color')->where([['id','in',$data['order_color_ids']]])->update(['status'=>2]);
                    if(!empty($old_order_color_ids))Db::name('wh_order_color')->where([['id','in',$old_order_color_ids]])->update(['status'=>1]);
                }

                $data['id'] = $id;
                if($data['status']<0)$data['status'] = 0;
                unset($data['create_time']);
                unset($data['material_sn']);
                $re = MaterialModel::update($data);
                $data['material_sn'] = $info['material_sn'];
            }
            else {
                if(!empty($data['order_color_ids']))Db::name('wh_order_color')->where([['id','in',$data['order_color_ids']]])->update(['status'=>2]);
                if(!empty($old_order_color_ids))Db::name('wh_order_color')->where([['id','in',$old_order_color_ids]])->update(['status'=>1]);
                $re = MaterialModel::create($data);
                $data['id'] = $re['id'];

                //关联预采购单
                if(!empty($ainp_id))Db::name('wh_material_ainp')->where(['id'=>$ainp_id])->update(['material_sn'=>$data['material_sn']]);
            }
            $data['number'] = 0;
            foreach ($lists as &$v){
                if(empty($v['material_name']))$v['material_name'] = $v['model'];
                if(!empty($v['order_id']))$v['archives_sn'] = Db::name('mill_order')->where([['id','=',$v['order_id']]])->value(['archives_sn']);
                //更新库存信息，厂家色号信息
                if(!empty($v['color_sn']) && !empty($data['supplier_color'][$v['color_sn']])){
                    $up_supplier = $data['supplier_color'][$v['color_sn']];

                    //如果供应商有更换，则进行厂家色号更换等处理
                    if($up_supplier['supplier_id'] != $v['supplier_id']){
                        //判断厂家色号是否已录入
                        $color_where = [
                            'model'             =>  $up_supplier['supplier_color'],
                            'supplier_id'       =>  $up_supplier['supplier_id'],
                            'type_id'           =>  $up_supplier['type_id'],
                        ];
                        $supplier_color = Db::name('wh_stock')->where($color_where)->find();

                        $supplier_color_add = [];
                        //替换
                        if($supplier_color){
                            $supplier_color_add['supplier_id'] = $supplier_color['supplier_id'];
                            $supplier_color_add['type_pid'] = $supplier_color['type_pid'];
                            $supplier_color_add['type_id'] = $supplier_color['type_id'];
                            $supplier_color_add['supplier_color'] = $supplier_color['model'];
                            $supplier_color_add['color_type_id'] = $supplier_color['color_type_id'];
                            $supplier_color_add['color_sn'] = $supplier_color['color_sn'];
                            $supplier_color_add['stock_id'] = $supplier_color['id'];
                            $supplier_color_add['stock_sn'] = $supplier_color['stock_sn'];
                            $supplier_color_add['heat'] = $supplier_color['heat'];

                            //重新组装厂家色号信息，采购量等
                            //if(!empty($data['supplier_color'][$supplier_color['color_sn']]))
                        }
                        //新增
                        else{
                            $supplier_color = Db::name('wh_stock')->where(['stock_sn'=>$up_supplier['stock_sn']])->find();

                            //新增厂家颜色
                            unset($supplier_color['id']);
                            $supplier_color['supplier_id'] = $up_supplier['supplier_id'];
                            $supplier_color['color_sn'] = ColorModel::getColorSn($supplier_color['type_id'],$supplier_color['heat']);

                            $supplier_color_add['supplier_id'] = $up_supplier['supplier_id'];
                            $supplier_color_add['type_pid'] = $supplier_color['type_pid'];
                            $supplier_color_add['type_id'] = $supplier_color['type_id'];
                            $supplier_color_add['supplier_color'] = $supplier_color['model'];
                            $supplier_color_add['color_type_id'] = $supplier_color['color_type_id'];
                            $supplier_color_add['color_sn'] = $supplier_color['color_sn'];
                            $supplier_color_add['stock_sn'] = StockModel::getStockSn($supplier_color);
                            $supplier_color_add['stock_id'] = Db::name('wh_stock')->where(['stock_sn'=>$supplier_color_add['stock_sn']])->value('id');
                            $supplier_color_add['heat'] = $supplier_color['heat'];
                        }
                        //厂家色号信息
                        Db::name('wh_order_color')->where([['color_sn','=',$v['color_sn']],['order_id','in',$data['order_ids']]])->update($supplier_color_add);

                        //重置采购单信息
                        $v = array_merge($v,$supplier_color_add);
                        $v['material_name'] = $supplier_color['title'];
                    }

                    //重新分配定量
                    $count = $up_supplier['count'];
                    if($count > 1){
                        $v['number'] = intval($up_supplier['number']/$count);
                        $data['supplier_color'][$up_supplier['color_sn']]['number'] -= $v['number'];
                    }
                    else $v['number'] = $up_supplier['number'];
                    $data['supplier_color'][$up_supplier['color_sn']]['count'] --;
                }
                //如果批号存在，则判断是否有库存，有库存则生成新的库存编号
                if(!empty($v['lot_sn'])){
                    $update_stock = [
                        'lot_sn'    =>  $v['lot_sn'],
                        'model2'    =>  $v['lot_sn'],
                    ];
                    $v['is_where'] = true;
                    $stock_where = StockModel::getStockSn($v);
                    unset($v['is_where']);

                    //如果批号被修改，则更新库存的批号
                    if(!empty($v['id'])){
                        $goods = Db::name('wh_material_goods')->where(['id'=>$v['id']])->find();
                        if($v['lot_sn'] != $goods['lot_sn'])Db::name('wh_stock')->where(['stock_sn'=>$goods['stock_sn']])->update($update_stock);
                    }

                    //获取相同批号的库存，没有则获取没批号的库存
                    $stock = Db::name('wh_stock')->where($stock_where)->where(['model2'=>$v['lot_sn']])->find();
                    if(empty($stock))$stock = Db::name('wh_stock')->where($stock_where)->where(['number'=>0,'model2'=>''])->find();
                    //如果库存 > 0，则生成新库存
                    //如果库存 = 0，且批号不同，则生成新库存
                    //if($stock['number'] > 0 || ($stock['number'] == 0 && $stock['lot_sn'] == '')){
                    //都没有，则生成新的库存
                    if(empty($stock)){
                        $v['model2'] = $v['lot_sn'];
                        $v['stock_sn'] = StockModel::getStockSn($v);
                    }
                    else {
                        $v['stock_sn'] = $stock['stock_sn'];
                    }
                    unset($v['model2']);

                    Db::name('wh_stock')->where(['stock_sn'=>$v['stock_sn']])->update($update_stock);
                }
                else $v['stock_sn'] = StockModel::getStockSn($v);

                //更新库存信息
                Db::name('wh_stock')->where(['stock_sn'=>$v['stock_sn']])->update(['title'=>$v['material_name']]);
                //同步新增同规格不同物料类别的库存
                $stock = Db::name('wh_stock')->where(['stock_sn'=>$v['stock_sn']])->find();
                StockModel::addSameStock($v['stock_sn'],$stock);

                if(!empty($v['id']))MaterialGoodsModel::update($v);
                else {
                    $v['material_id'] = $data['id'];
                    $v['material_sn'] = $data['material_sn'];
                    if(!empty($data['status']))$v['status'] = $data['status'];
                    $v['create_time'] = time();

                    MaterialGoodsModel::create($v);
                }
                $data['number'] += floatval($v['number']);
                $data['supplier_id'] = $v['supplier_id'];
            }

            Db::name('wh_material')->where([['id','in',$data['id']]])->update(['number'=>$data['number'],'supplier_id'=>$data['supplier_id']]);

            if($re)$this->success('操作成功', cookie('__forward2__'));
            $this->error('操作失败');
        }

        //数据
        if($id){
            $info = Db::name('wh_material')->where(['id'=>$id])->find();
            $info['is_order_color'] = $info['order_ids'];

            $type_pid = $info['type_pid'];

            if(!empty($info['order_ids']) && in_array($type_pid,ColorModel::$type_pid_arr)){
                if(!empty($order_ids))$info['order_ids'] = $order_ids;
                $info['order_color_ids'] = '';
                $info['lists'] = Db::name('mill_order')->where([['id','in',$info['order_ids']]])->select();
                foreach ($info['lists'] as &$v){
                    //总面积
                    $v['row_area'] = 0;
                    $where = [
                        ['g.order_id','=',$v['id']],
                        ['g.material_id','=',$info['id']],
                    ];
                    $v['lists'] = Db::name('wh_material_goods')
                        ->alias('g')
                        ->field('g.*,o.archives_sn,o.engineering,s.title as supplier,st.title as type_name,ct.title as color_type_name')
                        ->leftJoin('mill_order o','g.order_id=o.id')
                        //->leftJoin('wh_order_color c','g.color_id=c.id')
                        ->leftJoin('wh_supplier s','g.supplier_id=s.id')
                        ->leftJoin('wh_stock_type st','g.type_id=st.id')
                        ->leftJoin('wh_supplier_color_type ct','g.color_type_id=ct.id')
                        ->where($where)
                        ->order('g.id asc')
                        ->select();
                    foreach ($v['lists'] as &$vv){
                        //供应商
                        $v['supplier'] = $vv['supplier'];
                        $info['supplier_id'] = $vv['supplier_id'];
                        //总面积
                        $v['row_area'] += $vv['row_area'];
                        $info['row_area'] += $vv['row_area'];
                        //采购量
                        $info['number'] += $vv['number'];
                        //订单颜色ID
                        $info['order_color_ids'] .= ",{$vv['order_color_id']}";
                        //获取库存
                        $vv['sum_number'] = StockModel::getSumNumber($vv);
                    };
                }
            }
            else {
                $info['lists'] = Db::name('wh_material_goods')->where([['material_id','=',$info['id']]])->select();
                foreach ($info['lists'] as &$v){
                    //总面积
                    if(empty($v['row_area']))$v['row_area'] = 0;
                    //获取库存
                    $v['sum_number'] = StockModel::getSumNumber($v);
                    /*if($v['type_pid'] == 5){
                        $v['row_area2'] = $v['row_area'];
                        //理论重量
                        $v['kg'] = $v['long']*$v['high']*$v['row_area'];
                        //实际重量
                        $v['kg2'] = $v['long']*$v['high']*$v['row_area'];
                        //材质 order_id="+order_id+"&thickness="+
                        $type_text = floatval(Db::name('wh_stock_type')->where(['id'=>$v['type_id']])->value('title'));
                        $v['model_list'] = $this->getOrderArchives(['order_id'=>$v['order_id'],'thickness'=>$type_text,'re_type'=>1]);
                        foreach ($v['model_list'] as &$vv){
                            $vv['id'] = $vv['model'];
                            $vv['title'] = $vv['model'];
                            $vv['data_html'] = "data-row_area='{$vv['row_area']}'";
                        }
                    }*/

                }
            }

        }
        elseif ($ainp_id){
            $info = Db::name('wh_material_ainp')->where(['id'=>$ainp_id])->find();
            $info['id'] = '';
            $info['uid'] = UID;//申请人
            $info['material_sn'] = MaterialModel::getMaterialSn();//采购单编号
            $info['create_time'] = time();//创建日期
            $info['address_time'] = time();//到货时间
            $info['urgent_status'] = '';//加急状态

            $type_pid = $info['type_pid'];

            $info['lists'] = json_decode($info['goods'],true);
            $new_list = [];
            foreach ($info['lists'] as &$v){
                $v['stock_sn'] = '';
                $v['lot_sn'] = '';
                if(empty($v['num']))$v['num'] = 1;
                //获取库存
                $v['sum_number'] = StockModel::getSumNumber($v);

                for($i=$v['num'];$i>0;$i--){
                    $v['num'] = 1;
                    $new_list[] = $v;
                }

            }
            $info['lists'] = $new_list;
        }
        else{

            $info['id'] = '';
            $info['uid'] = UID;//申请人
            $info['material_sn'] = MaterialModel::getMaterialSn();//采购单编号
            $info['order_ids'] = $order_ids;//订单ID
            $info['order_color_ids'] = '';//订单颜色ID
            $info['type_pid'] = $type_pid;//采购类别 折弯，转印等
            $info['type_id'] = 1;//物料类型 暂时写死
            $info['row_area'] = 0;//总面积
            $info['number'] = 0;//采购量
            $info['note'] = '';//备注
            $info['create_time'] = time();//创建日期
            //$info['address_time'] = time();//到货时间
            $info['address_time'] = '';//到货时间
            $info['urgent_status'] = '';//加急状态
            $info['is_order_color'] = $is_order_color;//是否按确认颜色的工程来创建采购单 0:不按工程 1:按工程

            if($is_order_color && in_array($type_pid,ColorModel::$type_pid_arr)){
                $info['lists'] = Db::name('mill_order')->where([['id','in',$order_ids]])->select();

                foreach ($info['lists'] as &$v){
                    //总面积
                    $v['row_area'] = 0;
                    //颜色
                    $where = [['c.order_id','=',$v['id']],['c.type_pid','=',$type_pid]];
                    if(!empty($not_order_color_ids))$where[] = ['c.id','not in',$not_order_color_ids];
                    //$where[] = ['c.status','>=',1];
                    $v['lists'] = Db::name('wh_order_color')
                        ->alias('c')
                        ->field('c.*,c.color as material_name,sc.number as sum_number,o.archives_sn,o.engineering,s.title as supplier,st.title as type_name,ct.title as color_type_name')
                        ->leftJoin('mill_order o','c.order_id=o.id')
                        ->leftJoin('wh_stock sc','c.stock_id=sc.id')
                        ->leftJoin('wh_supplier s','c.supplier_id=s.id')
                        ->leftJoin('wh_stock_type st','c.type_id=st.id')
                        ->leftJoin('wh_supplier_color_type ct','c.color_type_id=ct.id')
                        ->where($where)
                        ->order('c.id asc')
                        ->select();
                    $v['supplier'] = '';
                    foreach ($v['lists'] as &$vv){
                        //供应商
                        $v['supplier'] = $vv['supplier'];
                        $info['supplier_id'] = $vv['supplier_id'];
                        //总面积
                        $v['row_area'] += $vv['row_area'];
                        $info['row_area'] += $vv['row_area'];
                        //采购量
                        $info['number'] += $vv['number'];
                        //订单颜色ID
                        $info['order_color_ids'] .= ",{$vv['id']}";
                        //获取库存
                        //$vv['sum_number'] = ColorModel::getSupplierColorNum($vv['color_id']);
                        //获取库存编号
                        //$vv['stock_sn'] = StockModel::getStockSn($vv,false);
                        //采购单ID
                        $vv['material_id'] = '';
                        $vv['type_pid'] = $info['type_pid'];
                        $vv['order_color_id'] = $vv['id'];
                        $vv['material_name'] = $vv['color'];
                        $vv['model'] = $vv['supplier_color'];
                        $vv['id'] = '';
                    };
                }
            }
            else{
                $info['lists'] = [[
                    'id'                =>  '',
                    'stock_id'          =>  '',
                    'stock_sn'          =>  '',
                    'material_id'       =>  '',
                    'order_id'          =>  '',
                    'supplier_id'       =>  '',
                    'type_pid'          =>  $type_pid,
                    'type_id'           =>  '',
                    'type_id2'          =>  '',
                    'type_id3'          =>  '',
                    'material_name'     =>  '',
                    'sum_number'        =>  '',
                    'number'            =>  '',
                    'model'             =>  '',
                    'model_list'        =>  [],
                    'long'              =>  '',
                    'high'              =>  '',
                    'quality'           =>  '',
                    'lot_sn'            =>  '',
                    'num'               =>  1,
                    'row_area'          =>  '',
                    'row_area2'         =>  '',
                    'kg'                =>  '',
                    'kg2'               =>  '',
                    'supplier_color'    =>  '',
                    'color_type_id'     =>  '',
                    'order_color_id'    =>  '',
                    'heat'              =>  0,
                    'color_sn'          =>  '',
                    'supplier_name'     =>  '',
                    'type_pname'        =>  '',
                    'type_name'         =>  '',
                    'color_type_name'   =>  '',
                ]];
            }
        }
        $info['stock_type'] = StockTypeModel::getGroup($type_pid);
        $info['stock_type2'] = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',array_keys($info['stock_type']))]]);
        $info['stock_type3'] = StockTypeModel::getGroup(0,false,[['pid','in',implode(',',array_keys($info['stock_type2']))]]);
        $info['supplier'] = SupplierModel::getGroup(0,$type_pid);
        $info['quality'] = ColorModel::getQuality($type_pid);
        $info['color_type'] = ColorModel::getColorType();
        $info['order'] = OrderModel::getList("CONCAT(engineering,' ',archives_sn,' ',batch)",['status'=>1]);
        $info['model_list'] = [];
        $info['order_color_ids'] = trim($info['order_color_ids'],',');

        //物料类型
        $tab_css = '';
        $list_tab = [];
        $type_list = StockTypeModel::getGroup(0,true);
        foreach ($type_list as $tlk=>$tlv){

            if($tlk == 8){
                unset($type_list[$tlk]);
                continue;
            }
            if(!$is_order_color && !in_array($tlk,ColorModel::$type_pid_arr)){
                unset($type_list[$tlk]);
                continue;
            }

            $get['id'] = $id;
            $get['is_order_color'] = $is_order_color;
            $get['type_pid'] = $tlk;
            $url_parm = '';
            //if(!empty($order_ids))$url_parm .= "?order_ids={$order_ids}";
            $list_tab[$tlk] = ['title' => $tlv['title'],'icon' => $tlv['icon'], 'url' => url('add', $get).$url_parm];

            $tab_css .= StockTypeModel::cssNavColor($tlk,$tlv['color']);

            if($id && $type_pid != $tlk)unset($list_tab[$tlk]);
        }

        $fromItems = MaterialModel::getTabFrom($type_pid,$info,$print);

        $method = ['method'=>'post','submit'=>'提交','isAjax'=>'ajax-post'];

        if(empty($info['id']) && empty($info['order_ids']) && $is_order_color && in_array($type_pid,ColorModel::$type_pid_arr))$method = ['method'=>'get','submit'=>'下一步','isAjax'=>'select-get'];

        if(empty($is_add))$method['isAjax'] = 'hidden';

        $css = "<style>
                .table-builder, .table-bordered > thead > tr > th {
                    background: #eff3f6;
                    color: #545454;
                }
                .nav2-pills > li.active > a, .nav2-pills > li.active > a:hover, .nav2-pills > li.active > a:focus, .nav2-pills > li > a:hover {
                    color: #5c90d2;
                    background-color: initial;
                    border-bottom: 1px solid #5c90d2;
                }
                
                {$tab_css}

                #table-selectorder > tbody > tr {border-bottom: 15px solid #eff3f6;}
                #table-selectorder2 > tbody > tr {border: 2px solid #43a3e5;}
                /*#table-selectorder > tbody {display: block;overflow: auto;height: 268px;}*/
                .btn-bottom-float {position: fixed;left: 0px;bottom: 10px;}
                .td-bg-color {background-color: #f9fafc}
                
                .dch-ul {width: 100%;padding: 0;margin: 0;}
                .dch-li {list-style-type: none;}
                .dch-bottom {border-bottom: 1px solid #f0f0f0;}
                
                
            </style>";

        //js
        $js = '<script type="text/javascript">

                $(".hidden-border-left-right").parent("td").css("border-left","hidden");
                $(".hidden-border-left-right").parent("td").css("border-right","hidden");
                
                //底部按钮浮动
                $(".select-get").parent().addClass("btn-bottom-float");
                
                //仅查看时，禁用部分操作功能
                var is_add = "'.$is_add.'";
                if(!is_add){
                    $(".add-btn").remove();
                    $("#form_group_order_add").remove();
                    $("#form_group_order").removeClass("col-lg-9");
                    $("#form_group_order").addClass("col-lg-12");
                    $("#form_group_sum").removeClass("col-lg-9");
                    $("#form_group_sum").addClass("col-lg-12");
                }
                
                $(".td-bg-color").parent("td").addClass("td-bg-color");
                $.each($(".td-width"),function(i) {
                    var width = $(this).data("width");
                    $(this).parents("td").css("width",width);
                });
                //搜索
                function ajax_search(obj) {
                    var form = $(obj).parents("#"+$(obj).data("form"));
                    var href = form.attr("action");
                    var select = "#table-"+form.data("select");
                    var pram = "";

                    $.each($("#"+$(obj).data("form")+" input"),function (i) {
                      if(pram == "")pram = "?"+this.name+"="+this.value;
                      else pram += "&"+this.name+"="+this.value;
                    });
                    
                    //搜索
                    $.ajax({
                        url: href+pram,
                        type: "GET"
                    }).done(function(data) {
                        //data = $.parseJSON(data);
                        $(select+" tbody").html(data);
                    });
                }
                //选中OR取消
                function select_order_ids(obj) {
                    var checkbox = $(obj).prop("checked");
                    var id = $(obj).val();
                    var html = "<tr>"+$(obj).parents("tr").html()+"</tr>";
                    var select = "#table-"+$(obj).data("select");
                    var select2 = "#table-"+$(obj).data("select2");
                    
                    //选中
                    if(checkbox){
                        $(select2+" tbody .empty").remove();
                        $(select2+" tbody ").append(html);
                        $(select2+" input[type=checkbox]").prop("checked", true);
                    }
                    //取消
                    else{
                        $(select+" input[value="+id+"]").prop("checked", false);
                        $(select2+" input[value="+id+"]").parents("tr").remove();
                        if($(select2+" tr").length == 0)$(select2+" tbody ").append("<tr class=\'empty\'><td class=\'text-center text-muted\'>暂无数据</td></tr>");
                    }
                    
                }
                //取消定量
                function select_order_del(obj) {
                    var href = $(obj).data("href");
                    var order_id = $(obj).data("order-id");
                    var pram = "?order_ids="+order_id;
                    
                    var checkbox_obj = $(obj).parents("tr").find(".select-order-ids");
                    var select = "#table-"+$(checkbox_obj).data("select");
                    //取消
                    $.ajax({
                        url: href+pram,
                        type: "GET"
                    }).done(function(data) {
                        checkbox_obj.prop("checked", true);
                        checkbox_obj.click();
                        $(select+" input[value="+order_id+"]").parents("tr").remove();
                    });
                }
                //下一步
                $("body").on("click",".select-get",function(){
                    var order_ids = "";
                    $.each($("#table-selectorder2 input[type=checkbox]:checked"),function(i) {
                        if(i == 0)order_ids = this.value;
                        else order_ids += ","+this.value;
                    });
                    if(!order_ids)Dolphin.notify("请选择工程", "danger");
                    else window.location.href = window.location.href+"?order_ids="+order_ids;
                    return false;
                    
                });
                
                //禁用输入框
                var type_pid = '.$type_pid.';
                $("input[name=\'goods[sum_number][]\']").attr("placeholder","自动获取库存");
                $("input[name=\'goods[sum_number][]\']").attr("disabled","disabled");
                /*//铝板
                if(type_pid == 5){
                    $("input[name=\'goods[row_area2][]\']").attr("placeholder","自动获取面积");
                    $("input[name=\'goods[row_area2][]\']").attr("disabled","disabled");
                    $("input[name=\'goods[kg][]\']").attr("placeholder","自动获取理论重量");
                    $("input[name=\'goods[kg][]\']").attr("disabled","disabled");
                    $("input[name=\'goods[kg2][]\']").attr("placeholder","自动获取实际重量");
                    $("input[name=\'goods[kg2][]\']").attr("disabled","disabled");
                }*/
                
                //删除
                function goods_del(obj) {
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        return false;
                    }
                    $(obj).parent().parent().remove();
                }
                //新增
                function goods_add(obj) {
                    var add = $(".goods").parent().parent().html();
                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                    $(".goods").parent("td").parent("tr:last").find("span.select2").remove();
                    $(".goods").parent("td").parent("tr:last").removeClass("hidden");
                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                    
                    App.initHelpers(["select2"]);
                }
                //查询库存
                function sum_number_show(obj) {
                    var tr_obj = $(obj).parents("tr");
                    var num_obj = $(tr_obj).find("input[name=\'goods[sum_number][]\']");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var type_id = tr_obj.find("select[name=\'goods[type_id][]\']").val();
                    var supplier_id = tr_obj.find("select[name=\'goods[supplier_id][]\']").val();
                    var model = tr_obj.find("input[name=\'goods[model][]\']").val();
                    //查询库存
                    $.ajax({
                        url: "'.url("getSumNumber").'?type_id="+type_id+"&type_pid="+type_pid+"&supplier_id="+supplier_id+"&model="+model,
                        type: "GET"
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        
                        num_obj.val(data.sum_number);
                    });
                }
                //获取材质
                //物料类别,订单选择事件
                $("body").on("change","select[name=\'goods[order_id][]\'],select[name=\'goods[type_id][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var order_id = tr_obj.find("select[name=\'goods[order_id][]\']").val();
                    var type_id = tr_obj.find("select[name=\'goods[type_id][]\']").val();
                    var type_obj = tr_obj.find("select[name=\'goods[type_id][]\']").find("option[value=\'"+type_id+"\']");
                    var type_text = parseFloat(type_obj.html());
                    
                    /*//铝板
                    if(type_pid == 5){
                        var html = "";
                        if(order_id){
                            //根据订单ID，板厚查材质
                            $.ajax({
                                url: "'.url("getOrderArchives").'?order_id="+order_id+"&thickness="+type_text,
                                type: "GET"
                            }).done(function(data) {
                                data = $.parseJSON(data);
                                var list = data.list;
                                html = "<option></option>";
                                if(list.length > 0){
                                    $.each(list,function(i,v){
                                        html += "<option value=\'"+v.model+"\' data-row_area=\'"+v.row_area+"\'>"+v.model+"</option>";
                                    });
                                }
                                
                                tr_obj.find("select[name=\'goods[model][]\']").html(html);
                            });
                        }
                        else tr_obj.find("select[name=\'goods[model][]\']").html(html);
                        
                        if(!html)tr_obj.find("select[name=\'goods[model][]\']").val("");
                        
                        $("input[name=\'goods[long][]\']").trigger("keyup");
                    }*/
                });
                //计算总量
                //材质点击事件
                $("body").on("change","select[name=\'goods[model][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    /*//铝板
                    if(type_pid == 5){
                        $("input[name=\'goods[long][]\']").trigger("keyup");
                    }*/
                    
                });
                //长宽点击事件
                $("body").on("keyup","input[name=\'goods[long][]\'],input[name=\'goods[high][]\'],select[name=\'goods[model][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var long = tr_obj.find("input[name=\'goods[long][]\']").val();
                    var high = tr_obj.find("input[name=\'goods[high][]\']").val();
                    var model = tr_obj.find("select[name=\'goods[model][]\']").val();
                    var row_area = tr_obj.find("select[name=\'goods[model][]\']").find("option[value=\'"+model+"\']").data("row_area");
                    
                    long = parseFloat(long) || "";
                    high = parseFloat(high) || "";
                    row_area = parseFloat(row_area) || "";
                    
                    /*//铝板
                    if(type_pid == 5){
                        var kg = long*high*row_area;
                        var kg2 = long*high*row_area;
                        
                        tr_obj.find("input[name=\'goods[material_name][]\']").val(model);
                        tr_obj.find("input[name=\'goods[row_area][]\']").val(row_area);
                        tr_obj.find("input[name=\'goods[row_area2][]\']").val(row_area);
                        tr_obj.find("input[name=\'goods[kg][]\']").val(kg);
                        tr_obj.find("input[name=\'goods[kg2][]\']").val(kg2);
                    }*/
                });
                //长宽点击事件
                $("body").on("keyup","input[name=\'goods[long][]\'],input[name=\'goods[high][]\'],select[name=\'goods[model][]\']",function(){
                    var tr_obj = $(this).parents("tr");
                    var type_pid = tr_obj.find("input[name=\'goods[type_pid][]\']").val();
                    var long = tr_obj.find("input[name=\'goods[long][]\']").val();
                    var high = tr_obj.find("input[name=\'goods[high][]\']").val();
                    var model = tr_obj.find("select[name=\'goods[model][]\']").val();
                    var row_area = tr_obj.find("select[name=\'goods[model][]\']").find("option[value=\'"+model+"\']").data("row_area");
                    
                    long = parseFloat(long) || "";
                    high = parseFloat(high) || "";
                    row_area = parseFloat(row_area) || "";
                    
                    /*//铝板
                    if(type_pid == 5){
                        var kg = long*high*row_area;
                        var kg2 = long*high*row_area;
                        
                        tr_obj.find("input[name=\'goods[material_name][]\']").val(model);
                        tr_obj.find("input[name=\'goods[row_area][]\']").val(row_area);
                        tr_obj.find("input[name=\'goods[row_area2][]\']").val(row_area);
                        tr_obj.find("input[name=\'goods[kg][]\']").val(kg);
                        tr_obj.find("input[name=\'goods[kg2][]\']").val(kg2);
                    }*/
                });
                //供应商点击事件
                $("body").on("change","select[name=\'supplier_list\']",function(){
                    var tr_obj = $(this).parents("tr");
                    
                    //var type_id = tr_obj.find("select[name=\'goods[type_id][]\']").val();
                    var supplier_id = $(this).val();
                    
                    //获取供应商select
                    var supplier_id_obj = $("select[name=\'goods[supplier_id][]\']");
                    //获取供应商option框
                    var supplier_id_obj_option = $("select[name=\'goods[supplier_id][]\'] option[value=\'"+supplier_id+"\']");
                    //获取select插件
                    var select2 = supplier_id_obj.siblings(".select2").find(".select2-selection__rendered");
                    //更新select值
                    supplier_id_obj.val(supplier_id);//供应商select值
                    supplier_id_obj_option.attr("selected", true);//供应商option选中项
                    
                    //更新select插件
                    select2.attr("title", supplier_id_obj_option.html());//供应商select值
                    select2.html("<span class=\'select2-selection__clear\'>×</span>"+supplier_id_obj_option.html());//供应商option选中项
                    
                });
                
                //折弯新增工程点击事件
                $("body").on("change",".order_add",function(){
                    var val = $(this).val();
                    var option = $(this).find("option[value=\'"+val+"\']");
                    
                    $(".order_add_engineering").html(option.data("engineering"));
                    $(".order_add_row_area").html(option.data("row-area"));
                    $(".order_add_sales").html(option.data("sales"));
                    $(".order_add_back").html(option.data("back"));
                    
                    $(".order-add-a").data("order-id",val);
                    
                });
                
                //折弯
                var order_ids = "'.$order_ids.'";//已选择的订单
                var not_order_color_ids = "'.$not_order_color_ids.'";//已取消的定量
                //折弯新增工程
                function order_add(obj) {
                    var id = $(obj).data("id");
                    var order_id = $(obj).data("order-id");
                    //var order_ids = $(obj).data("order-ids");
                    var type_pid = $(obj).data("type-pid");
                    
                    if(!order_id)Dolphin.notify("请选择工程", "danger");
                    else{
                        
                        var href = window.location.href;
                        var href_p = new RegExp("order_ids="+order_ids,"g");
                        
                        if(order_ids)order_ids = ","+order_ids+",";
                        //去重
                        var order_ids_test = order_ids.indexOf(","+order_id+",");
                        
                        if(order_ids_test < 0)order_ids += order_id;
                        //去掉首尾逗号
                        order_ids = order_ids.replace(/(^,)|(,$)/g,"");
                        //替换链接地址上的旧order_ids
                        href = href.replace(href_p, "order_ids="+order_ids);
                        if(href.indexOf("order_id")<0)href += "?order_ids="+order_ids;
                        if(href.indexOf("order_id")>0 && not_order_color_ids)href += "&not_order_color_ids="+not_order_color_ids;
                        window.location.href = href;
                    }
                }
                //折弯删除工程
                function order_del(obj) {
                    var order_id = $(obj).data("order-id");
                    //var order_ids = $(obj).data("order-ids");
                    var href_p = new RegExp("order_ids="+order_ids,"g");
                    var length = $(".goods_del").parent("td").parent("tr").length;
                    
                    if(length == 1){
                        //return false;
                        //Dolphin.notify("请选择工程", "danger");
                    }
                    
                    order_ids = ","+order_ids+",";
                    order_ids = order_ids.replace(","+order_id+",",",");
                    //去掉首尾逗号
                    order_ids = order_ids.replace(/(^,)|(,$)/g,"");
                    
                    var href = window.location.href;
                    
                    //替换链接地址上的旧order_ids
                    if(order_ids){
                        href = href.replace(href_p, "order_ids="+order_ids);
                        
                        if(href.indexOf("order_id")<0 && order_ids)href += "?order_ids="+order_ids;
                        if(not_order_color_ids)href += "&not_order_color_ids="+not_order_color_ids;
                    }
                    else{
                        href = href.substring(0,href.indexOf("?"));
                    }
                    if (href.substr(-1) === "?")href = href.replace("?","");
                    if (href.substr(-1) === "&")href = href.replace("&","");
                    window.location.href = href;
                }
                
                //折弯取消定量
                function order_color_del(obj) {
                    var order_color_id = $(obj).data("order-color-id");
                    
                    var href = window.location.href;
                    var href_p = new RegExp("not_order_color_ids="+not_order_color_ids,"g");
                    
                    if(not_order_color_ids)not_order_color_ids = ","+not_order_color_ids+",";
                    
                    //去重
                    var color_ids_test = not_order_color_ids.indexOf(","+order_color_id+",");
                    
                    if(color_ids_test < 0)not_order_color_ids += order_color_id;
                    //去掉首尾逗号
                    not_order_color_ids = not_order_color_ids.replace(/(^,)|(,$)/g,"");
                    //替换链接地址上的旧order_ids
                    if(not_order_color_ids)href = href.replace(href_p, "not_order_color_ids="+not_order_color_ids);
                    else href = href.replace(href_p, "");
                    if(href.indexOf("order_id")<0)href += "?order_ids="+order_ids;
                    if(href.indexOf("order_id")>0 && href.indexOf("not_order_color_ids")<0 && not_order_color_ids)href += "&not_order_color_ids="+not_order_color_ids;
                    
                    window.location.href = href;
                }
                
                //厂家色号，子窗口赋值
                function setSupplierColor(rel){
                    this.rel=rel;
                    //赋值处理
                    supplier_color_show(rel);
                }
                //厂家色号，子窗口获取值
                function getSupplierColor(){
                    return rel;
                }
                //打开厂家色号列表
                function supplier_color_list(obj) {
                    var color_obj = $(obj).prev("input[name=\'goods[supplier_color][]\']");
                    var type_pid = $(obj).siblings("input[name=\'goods[type_pid][]\']").val();
                    //厂家色号
                    var color = color_obj.val();
                    //地址
                    //var href = $(obj).data("href")+"?_s=c.title="+color+"&_o=c.title=like";
                    var href = $(obj).data("href")+"?_s=c.model="+color+"|c.type_pid="+type_pid+"&_o=c.model=like|c.type_pid=eq";
                    //当前点击事件的索引
                    var index = $("input[name=\'goods[supplier_color][]\']").index(color_obj);
                    href = href.replace(/__parent_i__/,index);
                    $(obj).attr("href",href);
                }
                //查询厂家色号对应供应商
                function supplier_color_show(rel) {
                    var obj = $("input[name=\'goods[supplier_color][]\']").eq(rel._parent_i);
                    
                    //查询厂家色号对应供应商
                    $.ajax({
                        url: \''.url("getSupplier").'?id=\'+rel.id,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        var supplier = data.supplier;
                        
                        if(!data.supplier)Dolphin.notify("查询无该色号，请填写后续信息！", "danger");
                        else{
                            //Dolphin.notify("已有该厂家色号，请选择供应商！", "success");
                            
                            //自动填充
                            obj.val(supplier.model);
                            $(obj).siblings("input[name=\'goods[stock_sn][]\']").val(supplier.stock_sn);
                            
                            $(obj).siblings("input[name=\'goods[model][]\']").val(supplier.model);
                            $(obj).siblings("input[name=\'goods[material_name][]\']").val(supplier.title);
                            $(obj).parent().parent().parent().find(".material_name").text(supplier.title);
                            
                            $(obj).siblings("input[name=\'goods[supplier_id][]\']").val(supplier.supplier_id);
                            $(obj).parent().parent().parent().find(".supplier_title").text(supplier.supplier_title);
                            
                            $(obj).siblings("input[name=\'goods[type_pid][]\']").val(supplier.type_pid);
                            $(obj).parent().parent().parent().find(".type_ptitle").text(supplier.type_ptitle);
                            
                            $(obj).siblings("input[name=\'goods[type_id][]\']").val(supplier.type_id);
                            $(obj).parent().parent().parent().find(".type_title").text(supplier.type_title);
                            
                            $(obj).siblings("input[name=\'goods[type_id2][]\']").val(supplier.type_id2);
                            $(obj).parent().parent().parent().find(".type_title2").text(supplier.type_title2);
                            
                            $(obj).siblings("input[name=\'goods[type_id3][]\']").val(supplier.type_id3);
                            $(obj).parent().parent().parent().find(".type_title3").text(supplier.type_title3);
                            
                            $(obj).siblings("input[name=\'goods[heat][]\']").val(supplier.heat);
                            $(obj).parent().parent().parent().find(".heat_title").text(supplier.heat_title);
                            
                            $(obj).siblings("input[name=\'goods[color_type_id][]\']").val(supplier.color_type_id);
                            $(obj).parent().parent().parent().find(".color_type_title").text(supplier.color_type_title);
                            
                            $(obj).siblings("input[name=\'goods[color_sn][]\']").val(supplier.color_sn);
                            $(obj).parent().parent().parent().find(".color_sn").text(supplier.color_sn);
                            
                            $(obj).parent().parent().parent().find(".sum_number").text(supplier.number);
                            
                        }
                    });
                            
                }
                
                //上传文件成功后的回调
                var dp_file_upload_success_material_file = function () {
                    //文档ID
                    var material_file = $("input[name=material_file]").val();
                    //获取文档信息并编译
                    $.ajax({
                        url: \''.url("materialFile",['pid'=>$type_pid]).'?id=\'+material_file,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        
                        //更新采购单信息
                        var order = [];
                        if(data.order.lists[0]){
                            order = data.order.lists[0];
                            $(".material_sn").text(order.material_sn);
                            $("input[name=material_sn]").val(order.material_sn);
                        }
                        
                        //更新采购明细信息
                        if(data.lists){
                            var lists = data.lists;
                            
                            var add = $(".goods").parent().parent().html();
                            
                            $.each(lists,function(i,v){
                                v["material_name"] = "铝板";
                                v["model"] = v["high"]+"*"+v["long"];
                                
                                //没有对应序号的采购铝板，则新增
                                if($(".goods").parent("td").parent("tr").eq(i).length < 1){
                                    add = "<tr class=\'hidden\'>"+add+"</tr>";
                                    $(add).insertAfter($(".goods").parent("td").parent("tr:last"));
                                    $(".goods").parent("td").parent("tr:last").find("input[name=\'goods[id][]\']").val("");
                                }
                                
                                var obj = $(".goods").parent("td").parent("tr").eq(i);
                                
                                obj.find("span.select2").remove();
                                //覆盖原有的值
                                obj.find("input[name=\'goods[long][]\']").val(v["long"]);
                                obj.find("input[name=\'goods[high][]\']").val(v["high"]);
                                obj.find("input[name=\'goods[row_area][]\']").val(v["row_area"]);
                                obj.find("input[name=\'goods[material_name][]\']").val(v["material_name"]);
                                obj.find("input[name=\'goods[model][]\']").val(v["model"]);
                                obj.find("input[name=\'goods[num][]\']").val(v["num"]);
                                obj.find("input[name=\'goods[number][]\']").val(v["number"]);
                                
                                //获取供应商select框
                                var supplier_id_obj = obj.find("select[name=\'goods[supplier_id][]\']");
                                //判断是否需要新增option框，对应value值没有，则新增
                                if(obj.find("select[name=\'goods[supplier_id][]\'] option[value=\'"+v["supplier_id"]+"\']").length < 1){
                                    supplier_id_obj.append("<option value=\'"+v["supplier_id"]+"\'>"+v["supplier_id_title"]+"</option>");
                                }
                                //获取供应商option框
                                var supplier_id_obj_option = obj.find("select[name=\'goods[supplier_id][]\'] option[value=\'"+v["supplier_id"]+"\']");
                                //获取select插件
                                var select2 = supplier_id_obj.siblings(".select2").find(".select2-selection__rendered");
                                
                                //获取类别select框
                                var type_id_obj = obj.find("select[name=\'goods[type_id][]\']");
                                //判断是否需要新增option框，对应value值没有，则新增
                                if(obj.find("select[name=\'goods[type_id][]\'] option[value=\'"+v["type_id"]+"\']").length < 1){
                                    type_id_obj.append("<option value=\'"+v["type_id"]+"\'>"+v["type_id_title"]+"</option>");
                                }
                                //获取类别option框
                                var type_id_obj_option = obj.find("select[name=\'goods[type_id][]\'] option[value=\'"+v["type_id"]+"\']");
                                //获取select插件
                                var select3 = type_id_obj.siblings(".select2").find(".select2-selection__rendered");
                                
                                //更新select值
                                supplier_id_obj.val(v["supplier_id"]);//供应商select值
                                supplier_id_obj_option.attr("selected", true);//供应商option选中项
                                type_id_obj.val(v["type_id"]);//类别select值
                                type_id_obj_option.attr("selected", true);//类别option选中项
                                
                                //更新select插件
                                select2.attr("title", v["supplier_id_title"]);//供应商select值
                                select2.html("<span class=\'select2-selection__clear\'>×</span>"+v["supplier_id_title"]);//供应商option选中项
                                select3.attr("title", v["type_id_title"]);//类别select值
                                select3.html("<span class=\'select2-selection__clear\'>×</span>"+v["type_id_title"]);//类别option选中项
                                
                                obj.removeClass("hidden");
                                
                            });
                                
                            App.initHelpers(["select2"]);
                        }
                        
                        //更新统计信息
                        if(data.group){
                            lists = data.group;
                            
                            var num_sum = 0;
                            var number_sum = 0;
                            var row_area_sum = 0;
                            $.each(lists,function(i,v){
                                num_sum += parseFloat(v["num_sum"]);
                                number_sum += parseFloat(v["number_sum"]);
                                row_area_sum += parseFloat(v["row_area_sum"]);
                            })
                            
                            $(".num_sum").text(num_sum);
                            $(".number_sum").text(number_sum);
                            $(".row_area_sum").text(row_area_sum);
                        }
                        
                    });
                };
            </script>';

        $title = '新建采购单';
        if($id)$title = '采购单详情';
        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->setTabNav2($list_tab,$type_pid)
            ->addHidden('uid')
            ->addHidden('order_ids')
            ->addHidden('order_color_ids')
            ->addHidden('supplier_id')
            ->addHidden('type_pid')
            ->addHidden('type_id')
            ->addHidden('row_area')
            ->addHidden('number')
            ->addHidden('status')
            ->addSelect('','仅加载select插件用','', $info['supplier'],'','','hidden')
            ->addDate('','仅加载date插件用','', '','','','hidden')
            ->addFormItems($fromItems)
            ->setFormData($info)
            ->setExtraJs($js)
            ->setExtraCss($css)
            ->hideBtn(['submit', 'back'])
            ->method($method['method'])
            ->addBtn('<button type="submit" class="btn btn-radius btn-lg btn-minlg btn-primary '.$method['isAjax'].'" target-form="form-builder" >'.$method['submit'].'</button>')
            ->addBtn('<button type="button" class="btn btn-radius btn-lg btn-minlg bg-info-light" onclick="window.location.href=\''.cookie('__forward__').'\';return false;">返回</button>')
            ->layout(['note'=>12])
            ->fetch();

    }

    //不按工程新建油漆类采购单
    public function add2($id=null)
    {
        return $this->add();
    }

    //详情
    public function show(){
        return $this->add(false);
    }

    //获取库存
    public function getSumNumber(){

        $input = input();

        $sum_number = StockModel::getSumNumber($input);

        echo json_encode(['sum_number'=>$sum_number],JSON_UNESCAPED_UNICODE);exit;
    }

    //获取面积表信息
    public function getOrderArchives($input = [],$group = ''){

        $re_type = '';
        if(empty($input))$input = input();
        if(!empty($input['group']))$group = $input['group'];
        if(!empty($input['re_type']))$re_type = $input['re_type'];

        $where = [['order_id','=',$input['order_id']]];
        if($input['thickness'])$where[] = ['thickness','=',$input['thickness']];

        $field = 'id,model,SUM(row_area) as row_area';
        $list = ArchivesModel::getList($input['order_id'],$field,'sort asc',$group,[],$where);
        if(empty($list[0]['id']))$list = [];

        if($re_type == 1)return $list;
        echo json_encode(['list'=>$list],JSON_UNESCAPED_UNICODE);exit;
    }

    /**
     * 选择批次
     * @return mixed
     */
    public function selectOrder()
    {
        $search = input('search');
        $type_pid = input('type_pid');

        $where = '';

        if(!empty($search)){
            $where = " o.engineering like '%{$search}%' OR o.archives_sn like '%{$search}%' ";
        }

        $fromItems = MaterialModel::fromSelect($type_pid,true,$where);

        $html = '';

        $commplextable = new Builder();
        $data = $commplextable->item('','',$fromItems['data']);

        foreach ($data['data'] as $v){
            $html .= '<tr>';
            foreach ($v as $vo){

                $style = 'vertical-align: middle; ';
                if(is_array($vo["value"]))$style .= 'padding:0;';
                $rowspan = '';
                if(!empty($vo['rowspan']))$rowspan = "rowspan='{$vo['rowspan']}'";
                $colspan = '';
                if(!empty($vo['colspan']))$colspan = "colspan='{$vo['colspan']}'";

                $html .= "<td style='{$style}' {$rowspan} {$colspan}>{$vo['value']}</td>";
            }
            $html .= '</tr>';
        }

        exit($html);
    }

    //取消颜色定量
    public function rationSubs(){
        $action = new Color();

        return $action->rationSubs();
    }

    /**
     * 删除
     * @return mixed
     */
    public function delete($record = [])
    {

        if ($this->request->isPost()) {
            $data = $this->request->post();

            $ids = $data['ids'];

            if(empty($ids))$this->error('请选择采购单');

            foreach ($ids as $id){
                $info = Db::name('wh_material')->where(['id'=>$id])->find();

                //获取库存编号，处理库存数据
                $stock_sns = Db::name('wh_material_goods')->where(['material_id'=>$id])->column('stock_sn');
                if(!empty($stock_sns)){
                    foreach ($stock_sns as $stock_sn){
                        //清空库存批号
                        StockModel::upStockNumber(3,$stock_sn);
                    }
                }

                Db::name('wh_material')->where(['id'=>$id])->delete();
                Db::name('wh_material_goods')->where(['material_id'=>$id])->delete();
                if(!empty($info['order_color_ids']))Db::name('wh_order_color')->where([['id','in',$info['order_color_ids']]])->update(['status'=>1]);
            }

            $this->success('操作成功');
        }

        $this->error('请选择采购单');

    }

    /**
     * 我发起的采购单
     */
    public function myList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        cookie('__forward2__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['m.status','<>',0];

        //------------------------------ 采购部权限 ----------------------------------
        //获取部门ID，采购部的只看自己的采购单
        //采购部ID：13,15
        $user_group = [13,15];
        //采购部的只看自己的采购单
        if(in_array(session('user_auth.group'),$user_group))$map[] = ['m.uid','=',UID];
        //只能查看角色权限内的物料类型采购单
        $type_pids = Db::name('admin_role')->where(['id'=>session('user_auth.role')])->value('stock_type_ids');
        if(!empty($type_pids))$map[] = ['m.type_pid','in',$type_pids];
        //获取第一个物料类型
        $type_pid = Db::name('wh_stock_type')->where([['status','=',1],['pid','=',0]])->order('sort asc,id asc')->value('id');

        // 数据列表
        $data_list = Db::name('wh_material')
            ->alias('m')
            ->field('m.*,s.title_abb as supplier_name,u.nickname,t.title as type_name')
            ->leftJoin('wh_supplier s','m.supplier_id=s.id')
            ->leftJoin('admin_user u','m.uid=u.id')
            ->leftJoin('wh_stock_type t','m.type_pid=t.id')
            ->where($map)
            ->order('m.id desc')
            ->paginate()
            ->each(function ($v){

                //采购单信息
                $html = '<tr class="new-title-w"><td colspan="10" style="height: 10px;padding: unset;"></td></tr>';
                $html .= '<tr class="new-title"><td colspan="10" style="background-color: #edf6fd;font-weight: 600;">';

                $html .= '<div style="float: left">
                        <label class="css-input css-checkbox css-checkbox-primary"><input class="ids" type="checkbox" name="ids[]" value="'.$v['id'].'"><span></span></label>
                        采购单号：'.$v['material_sn'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;申请人：'.$v['nickname'].'</div>';
                $html .= '<div style="float: right;margin-right: 40px"><a style="color: #3152ef;" href="'.url('show', [ 'id' => $v['id']]).'">采购单详情</a></div>';

                $html .= '</td></tr>';

                $v['title'] = $html;

                //明细
                $v['goods_list'] = Db::name('wh_material_goods')
                    ->where(['material_id'=>$v['id']])
                    ->group('stock_sn')
                    ->order('id asc')
                    ->select();

                //供应商
                $v['supplier_name'] = Db::name('wh_material_goods')
                    ->alias('g')
                    ->leftJoin('wh_supplier s','s.id=g.supplier_id')
                    ->where(['g.material_id'=>$v['id']])
                    ->group('s.id')
                    ->column('s.title_abb');
                $v['supplier_name'] = implode(',<br>',$v['supplier_name']);

                //打印状态
                $v['note'] .= MaterialModel::urgent_status_color($v['code_print_status'],MaterialModel::$code_print_status[$v['code_print_status']]);

                $goods_list_html = '<ul class="dch-ul">';
                foreach ($v['goods_list'] as $gv){
                    //列表表头
                    switch ($v['type_pid']){
                        //油漆库
                        case in_array($v['type_pid'],ColorModel::$type_pid_arr):
                            $goods_list_html .= "<li class='dch-li'>厂家色号：<span class='tab-text-info'>{$gv['model']}</span> | 颜色：<span class='tab-text-info'>{$gv['material_name']}</span></li>";
                            break;
                        //铝卷
                        case 4:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span> | 批号：<span class='tab-text-info'>{$gv['lot_sn']}</span></li>";
                            break;
                        //铝板
                        case 5:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span></li>";
                            break;
                        //原材料
                        case 3:
                            //化工
                        case 6:
                            //其他
                        case 7:
                        $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span> | 名称：<span class='tab-text-info'>{$gv['material_name']}</span></li>";
                            break;
                    }

                }
                $goods_list_html .= '</ul>';
                $v['goods_list'] = $goods_list_html;

                return $v;
            })
        ;

        $css = "<style>
                .dch-ul {width: 100%;padding: 0;margin: 0;}
                .dch-li {list-style-type: none;}
                .dch-bottom {border-bottom: 1px solid #f0f0f0;}
                
                
            </style>";
        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".hidden-remove").remove();
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('我发起的采购单') // 页面标题
            ->setTableName('wh_material') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'm.status', '采购状态', 'eq','',MaterialModel::$status],
                //['select:2', 'm.supplier_id', '供应商', 'eq','',SupplierModel::getGroup()],
                ['select:1', 'm.type_pid', '采购类型', 'eq','',StockTypeModel::getGroup()],
                ['text:2', 'm.material_sn', '采购单号', 'like'],
                ['daterange:2', 'm.create_time', '采购日期'],
            ])
            ->addTrClass('hidden-remove','title','<>','')
            ->hideColumn('title','remove')
            ->addColumns([ // 批量添加列
                ['title', ''],
                ['create_time', '采购日期','date'],
                ['supplier_name', '供应商'],
                ['number', '采购量(kg)'],
                ['type_name', '采购类型'],
                ['status','采购单状态','callback',function($value, $data){
                    $value = MaterialModel::status_bar_tag($value);
                    return $value;
                },'__data__'],
                ['urgent_status','紧急状态','callback',function($value, $data){
                    $value = MaterialModel::urgent_status_color($value,MaterialModel::$urgent_status[$value]);
                    return $value;
                },'__data__'],
                ['address_time','预计到货','callback',function($value, $data){
                    if($value)$value = ceil(($value-$data['create_time'])/86400);
                    if(empty($value))$value = '暂未设置';
                    else $value .= '天';
                    return $value;
                },'__data__'],
                ['goods_list', '明细'],
                ['note', '备注'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraCss($css)
            ->setExtraJs($js)
            //->addTopButton('selectOrder',['title' => '新增采购单','href' => url('selectOrder'),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '40%'], 'title' => ['新增采购单', 'font-size:24px;text-align: center;']])
            //->addTopButton('add2',['title' => '直接新增采购单','href' => url('add',['is_order_color'=>0,'type_pid'=>1]),'icon'=>'','class'=>'btn btn-primary'])
            ->addTopButton('add',['title' => '新增采购单','href' => url('add',['type_pid'=>$type_pid]),'icon'=>'','class'=>'btn btn-primary'])
            ->addTopButton('delete',['title' => '删除','icon'=>'','class'=>'btn bg-info-light ajax-post confirm'])
            ->addRightButton('add', ['title' => '编辑', 'href' => url('add', [ 'id' => '__id__']), 'icon' => ''])
            //->addRightButton('show', ['title' => '查看', 'href' => url('add', [ 'id' => '__id__']), 'icon' => ''])
            ->addRightButton('showPrint',['title' => '导出','href' => url('showPrint',['id'=>'__id__','print'=>'2']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])
            ->addRightButton('showPrint',['title' => '打印','href' => url('showPrint',['id'=>'__id__','print'=>'1']),'class'=>'btn bg-info-light disable-dch','icon'=>'','target'=>'_blank'])
            ->addRightButton('codePrint',['title' => '打印条码','href' => url('wh/stock/codePrint',['material_id' => '__id__','page'=>1]),'class'=>'btn bg-info-light disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'goods_list'  => 300,
                //'note'  => 300,
                'mobile'  => 80,
                'sales_mobile'  => 80,
                'address'  => 150,
                'status'  => 280,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 待审核采购单列表页
     * @return mixed
     */
    public function myVerify()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['m.status','=',0];
        // 数据列表
        $data_list = Db::name('wh_material')
            ->alias('m')
            ->field('m.*,s.title as supplier_name,u.nickname,t.title as type_name')
            ->leftJoin('wh_supplier s','m.supplier_id=s.id')
            ->leftJoin('admin_user u','m.uid=u.id')
            ->leftJoin('wh_stock_type t','m.type_pid=t.id')
            ->where($map)
            ->order('m.id desc')
            ->paginate()
            ->each(function ($v){

                //采购单信息
                $html = '<tr class="new-title-w"><td colspan="10" style="height: 10px;padding: unset;"></td></tr>';
                $html .= '<tr class="new-title"><td colspan="10" style="background-color: #edf6fd;font-weight: 600;">';

                $html .= '<div style="float: left">
                        <label class="css-input css-checkbox css-checkbox-primary"><input class="ids" type="checkbox" name="ids[]" value="'.$v['id'].'"><span></span></label>
                        采购单号：'.$v['material_sn'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;申请人：'.$v['nickname'].'</div>';
                $html .= '<div style="float: right;margin-right: 40px"><a style="color: #3152ef;" href="'.url('show', [ 'id' => $v['id']]).'">采购单详情</a></div>';

                $html .= '</td></tr>';

                $v['title'] = $html;

                //明细
                $v['goods_list'] = Db::name('wh_material_goods')
                    ->where(['material_id'=>$v['id']])
                    ->group('stock_sn')
                    ->order('id asc')
                    ->select();

                $goods_list_html = '<ul class="dch-ul">';
                foreach ($v['goods_list'] as $gv){
                    //列表表头
                    switch ($v['type_pid']){
                        //油漆库
                        case in_array($v['type_pid'],ColorModel::$type_pid_arr):
                            $goods_list_html .= "<li class='dch-li'>厂家色号：<span class='tab-text-info'>{$gv['model']}</span> | 颜色：<span class='tab-text-info'>{$gv['material_name']}</span></li>";
                            break;
                        //铝卷
                        case 4:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span> | 批号：<span class='tab-text-info'>{$gv['lot_sn']}</span></li>";
                            break;
                        //铝板
                        case 5:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span></li>";
                            break;
                        //原材料
                        case 3:
                            //化工
                        case 6:
                            //其他
                        case 7:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span> | 名称：<span class='tab-text-info'>{$gv['material_name']}</span></li>";
                            break;
                    }

                }
                $goods_list_html .= '</ul>';
                $v['goods_list'] = $goods_list_html;

                //供应商
                $v['supplier_name'] = Db::name('wh_material_goods')
                    ->alias('g')
                    ->leftJoin('wh_supplier s','s.id=g.supplier_id')
                    ->where(['g.material_id'=>$v['id']])
                    ->group('s.id')
                    ->column('s.title_abb');
                $v['supplier_name'] = implode(',<br>',$v['supplier_name']);
                return $v;
            })
        ;

        $css = "<style>
                .dch-ul {width: 100%;padding: 0;margin: 0;}
                .dch-li {list-style-type: none;}
                .dch-bottom {border-bottom: 1px solid #f0f0f0;}
                
                
            </style>";
        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".hidden-remove").remove();
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('我发起的采购单') // 页面标题
            ->setTableName('wh_material') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'm.status', '采购状态', 'eq','',MaterialModel::$status],
                //['select:2', 'm.supplier_id', '供应商', 'eq','',SupplierModel::getGroup()],
                ['select:1', 'm.type_pid', '采购类型', 'eq','',StockTypeModel::getGroup()],
                ['text:2', 'm.material_sn', '采购单号', 'like'],
                ['daterange:2', 'm.create_time', '采购日期'],
            ])
            ->addTrClass('hidden-remove','title','<>','')
            ->hideColumn('title','remove')
            ->addColumns([ // 批量添加列
                ['title', ''],
                ['create_time', '采购日期','date'],
                ['supplier_name', '供应商'],
                ['number', '采购量(kg)'],
                ['type_name', '采购类型'],
                ['status','采购单状态','callback',function($value, $data){
                    $value = MaterialModel::status_bar_tag($value);
                    return $value;
                },'__data__'],
                ['urgent_status','紧急状态','callback',function($value, $data){
                    $value = MaterialModel::urgent_status_color($value,MaterialModel::$urgent_status[$value]);
                    return $value;
                },'__data__'],
                ['address_time','预计到货','callback',function($value, $data){
                    if($value)$value = ceil(($value-$data['create_time'])/86400);
                    if(empty($value))$value = '暂未设置';
                    else $value .= '天';
                    return $value;
                },'__data__'],
                ['goods_list', '明细'],
                ['note', '备注'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraCss($css)
            ->setExtraJs($js)
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('notDisable',['id' => '__id__','field'=>'status']),'class'=>'btn bg-danger-light','icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->addRightButton('backEnable',['title' => '审核通过','href' => url('backEnable',['id' => '__id__']).'?fieldv=status|1','class'=>'btn bg-info-light ajax-get','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'goods_list'  => 300,
                //'note'  => 300,
                'mobile'  => 80,
                'sales_mobile'  => 80,
                'address'  => 150,
                'status'  => 280,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 待入库采购单列表页
     * @return mixed
     */
    public function myDoGoods()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map[] = ['m.status','>',0];
        $map[] = ['m.status','<',3];
        // 数据列表
        $data_list = Db::name('wh_material')
            ->alias('m')
            ->field('m.*,s.title as supplier_name,u.nickname,t.title as type_name')
            ->leftJoin('wh_supplier s','m.supplier_id=s.id')
            ->leftJoin('admin_user u','m.uid=u.id')
            ->leftJoin('wh_stock_type t','m.type_pid=t.id')
            ->where($map)
            ->order('m.id desc')
            ->paginate()
            ->each(function ($v){

                //采购单信息
                $html = '<tr class="new-title-w"><td colspan="10" style="height: 10px;padding: unset;"></td></tr>';
                $html .= '<tr class="new-title"><td colspan="10" style="background-color: #edf6fd;font-weight: 600;">';

                $html .= '<div style="float: left">
                        <label class="css-input css-checkbox css-checkbox-primary"><input class="ids" type="checkbox" name="ids[]" value="'.$v['id'].'"><span></span></label>
                        采购单号：'.$v['material_sn'].'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;申请人：'.$v['nickname'].'</div>';
                $html .= '<div style="float: right;margin-right: 40px"><a style="color: #3152ef;" href="'.url('myGoodsList', [ 'material_sn' => $v['material_sn']]).'">采购单详情</a></div>';

                $html .= '</td></tr>';

                $v['title'] = $html;

                //明细
                $v['goods_list'] = Db::name('wh_material_goods')
                    ->where(['material_id'=>$v['id']])
                    ->group('stock_sn')
                    ->order('id asc')
                    ->select();

                $goods_list_html = '<ul class="dch-ul">';
                foreach ($v['goods_list'] as $gv){
                    //列表表头
                    switch ($v['type_pid']){
                        //油漆库
                        case in_array($v['type_pid'],ColorModel::$type_pid_arr):
                            $goods_list_html .= "<li class='dch-li'>厂家色号：<span class='tab-text-info'>{$gv['model']}</span> | 颜色：<span class='tab-text-info'>{$gv['material_name']}</span></li>";
                            break;
                        //铝卷
                        case 4:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span> | 批号：<span class='tab-text-info'>{$gv['lot_sn']}</span></li>";
                            break;
                        //铝板
                        case 5:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span></li>";
                            break;
                        //原材料
                        case 3:
                            //化工
                        case 6:
                            //其他
                        case 7:
                            $goods_list_html .= "<li class='dch-li'>规格：<span class='tab-text-info'>{$gv['model']}</span> | 名称：<span class='tab-text-info'>{$gv['material_name']}</span></li>";
                            break;
                    }

                }
                $goods_list_html .= '</ul>';
                $v['goods_list'] = $goods_list_html;

                //供应商
                $v['supplier_name'] = Db::name('wh_material_goods')
                    ->alias('g')
                    ->leftJoin('wh_supplier s','s.id=g.supplier_id')
                    ->where(['g.material_id'=>$v['id']])
                    ->group('s.id')
                    ->column('s.title_abb');
                $v['supplier_name'] = implode(',<br>',$v['supplier_name']);
                return $v;
            })
        ;

        $css = "<style>
                .dch-ul {width: 100%;padding: 0;margin: 0;}
                .dch-li {list-style-type: none;}
                .dch-bottom {border-bottom: 1px solid #f0f0f0;}
                
                
            </style>";
        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".hidden-remove").remove();
                });
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('我发起的采购单') // 页面标题
            ->setTableName('wh_material') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                ['select:1', 'm.status', '采购状态', 'eq','',MaterialModel::$status],
                //['select:2', 'm.supplier_id', '供应商', 'eq','',SupplierModel::getGroup()],
                ['select:1', 'm.type_pid', '采购类型', 'eq','',StockTypeModel::getGroup()],
                ['text:2', 'm.material_sn', '采购单号', 'like'],
                ['daterange:2', 'm.create_time', '采购日期'],
            ])
            ->addTrClass('hidden-remove','title','<>','')
            ->hideColumn('title','remove')
            ->addColumns([ // 批量添加列
                ['title', ''],
                ['create_time', '采购日期','date'],
                ['supplier_name', '供应商'],
                ['number', '采购量(kg)'],
                ['type_name', '采购类型'],
                ['status','采购单状态','callback',function($value, $data){
                    $value = MaterialModel::status_bar_tag($value);
                    return $value;
                },'__data__'],
                ['urgent_status','紧急状态','callback',function($value, $data){
                    $value = MaterialModel::urgent_status_color($value,MaterialModel::$urgent_status[$value]);
                    return $value;
                },'__data__'],
                ['address_time','预计到货','callback',function($value, $data){
                    if($value)$value = ceil(($value-$data['create_time'])/86400);
                    if(empty($value))$value = '暂未设置';
                    else $value .= '天';
                    return $value;
                },'__data__'],
                ['goods_list', '明细'],
                ['note', '备注'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraCss($css)
            ->setExtraJs($js)
            ->addRightButton('myGoodsList',['title' => '查看详情','href' => url('myGoodsList',['material_sn' => '__material_sn__']),'class'=>'btn bg-info-light','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'goods_list'  => 300,
                //'note'  => 300,
                'mobile'  => 80,
                'sales_mobile'  => 80,
                'address'  => 150,
                'status'  => 280,
            ])
            ->fetch(); // 渲染模板
    }

    /**
     * 采购单产品明细
     */
    public function myGoodsList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $material_sn = urldecode(input('material_sn'));

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
            elseif(!empty($mv[0]) && $mv[0] == 'is_number' && !empty($mv[2])){
                $is_number = $mv[2];
                //无库存
                if($is_number == 1){
                    $map2 .= " and s.number = 0";
                }
                //有库存
                if($is_number == 2){
                    $map2 .= " and s.number > 0";
                }
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        $map[] = ['g.material_sn','=',$material_sn];
        //$map[] = ['g.status','<',3];
        // 数据列表
        $data_list = Db::name('wh_material_goods')
            ->alias('g')
            ->field('g.*,t.title as type_pname,tt.title as type_name,ss.title_abb as supplier_name')
            ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=g.type_pid')
            ->leftJoin('wh_stock_type tt','tt.id=g.type_id')
            ->leftJoin('wh_supplier ss','ss.id=g.supplier_id')
            ->where($map)
            ->where($map2)
            ->order('g.id asc')
            ->paginate()
            ->each(function ($v){

                //收货情况
                $v['num2'] = Db::name('wh_stock_log')->where(['material_sn'=>$v['material_sn'],'stock_sn'=>$v['stock_sn']])->sum('num');
                $v['number2'] = Db::name('wh_stock_log')->where(['material_sn'=>$v['material_sn'],'stock_sn'=>$v['stock_sn']])->sum('number');
                //未收货情况
                $v['not_num'] = floatval($v['num'])-floatval($v['num2']);
                if($v['not_num'] < 0)$v['not_num'] = 0;
                $v['not_number'] = floatval($v['number'])-floatval($v['number2']);
                if($v['not_number'] < 0)$v['not_number'] = 0;

                if($v['status'] != 3){
                    $v['not_num'] = '<input type="text" name="not_number" class="form-control input-sm" placeholder="请输入收货数量" value="'.$v['not_num'].'">';
                    $v['not_number'] = '<input type="text" name="not_num" class="form-control input-sm" placeholder="请输入收货数量" value="'.$v['not_number'].'">';
                }

                return $v;
            })
        ;

        //合计：库存，采购数量，采购重量，收货数量，收货重量
        //采购，库存去重求和：SUM(DISTINCT case when s.id then s.number else 0 end)
        $total = Db::name('wh_material_goods')
            ->alias('g')
            ->field('sum(g.num) as num,sum(g.number) as number')
            ->where($map)
            ->where($map2)
            ->find();
        //收货
        $total1 = Db::name('wh_material_goods')
            ->alias('g')
            ->field('sum(g.num) as num,sum(g.number) as number')
            ->where($map)
            ->where($map2)
            ->where('g.status>=2')
            ->find();

        $total_str = "采购数量：{$total['num']}(次)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;采购重量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['num']}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货重量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";

        $tab_js = '';
        //JS
        $js = '
            <script type="text/javascript">
                $(function() {
                    
                    //确认入库点击事件
                    $(".addJoin").click(function() {
                      var tr = $(this).parents("tr");
                      var num = $(tr).find("input[name=\'not_num\']").val();
                      var number = $(tr).find("input[name=\'not_number\']").val();
                      
                      var href = $(this).attr("href");
                      href += "?num="+num+"&number="+number;
                      $(this).attr("href",href);
                    });
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "采购单【'.$material_sn.'】明细",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                    
                })
            </script>';
        $js .= $tab_js;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("采购单【{$material_sn}】明细") // 页面标题
            ->setTableName('wh_material_goods') // 设置表名
            ->hideCheckbox()
            ->setPageTips($total_str,'info','topbtn')
            ->addColumns([ // 批量添加列
                ['create_time', '采购日期','date'],
                ['type_pname', '采购类型'],
                ['type_name', '类型'],
                ['material_name', '名称'],
                ['model', '规格'],
                ['supplier_name', '供应商'],
                ['number', '采购重量(kg)'],
                ['num', '采购数量'],
                ['number2', '已收货重量(kg)'],
                ['num2', '已收货数量'],
                ['not_number', '待收货重量(kg)'],
                ['not_num', '待收货数量'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addRightButton('addJoin',['title' => '确认入库','href' => url('wh/stock/addJoin',['material_sn' => '__material_sn__','stock_sn'=>'__stock_sn__','ajax_form'=>'post']),'class'=>'btn btn-primary disable-dch ajax-get confirm addJoin','icon'=>''])

            ->replaceRightButton(['status' => ['=',3]],'',['addJoin'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'batch'  => 60,
                'archives_number'  => 50,
                'color_type_id'     => 60,
                'number'     => 60,
                'status'     => 60,
                'number2'     => 60,
                'status2_sum'     => 74,
                'status3_sum'     => 74,
            ],80)
            ->fetch(); // 渲染模板
    }

    /**
     * 采购单明细
     */
    public function goodsList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $stock_type = $this->_type_id;
        $type_pid = $this->_type_pid;
        $list_tab = StockTypeModel::getTabNav('goodsList');

        foreach ($list_tab as $tlk=>$tlv){

            if($tlk == 8){
                unset($list_tab[$tlk]);
                continue;
            }
        }

        $supplier_list = SupplierModel::getGroup(0,$type_pid,'title_abb');

        // 获取查询条件
        $map = $this->getMap();
        $map2 = '';
        foreach ($map as $mk=>$mv){
            if(!empty($mv[0]) && $mv[0] == 's.model' && !empty($mv[2])){
                $arr = explode(',',trim($mv[2],'%'));
                $map2 .= " and (";
                foreach ($arr as $ak=>$av){
                    if(!empty($ak))$map2 .= " or ";
                    $map2 .= " s.model like '%{$av}%' ";
                }
                $map2 .= ")";
                unset($map[$mk]);
            }
            elseif(!empty($mv[0]) && $mv[0] == 'is_number' && !empty($mv[2])){
                $is_number = $mv[2];
                //无库存
                if($is_number == 1){
                    $map2 .= " and s.number = 0";
                }
                //有库存
                if($is_number == 2){
                    $map2 .= " and s.number > 0";
                }
                unset($map[$mk]);
            }
        }
        $map2 = trim(trim($map2),'and');
        $map = array_merge($map);
        if($stock_type)$map[] = ['g.type_id','=',$stock_type];
        else $map[] = ['g.type_pid','=',$type_pid];
        $map[] = ['g.status','>=',1];
        // 数据列表
        $data_list = Db::name('wh_material_goods')
            ->alias('g')
            ->field('g.*,g.number as number2,g.num as num2,o.archives_bill_time,o.engineering,o.batch,t.title as type_pname,tt.title as type_name,ss.title_abb as supplier_name,c.archives_number,c.archives_color,s.number as sum_number,s.num as sum_num')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('wh_order_color c','c.id=g.order_color_id')
            ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
            ->leftJoin('wh_stock_type t','t.id=g.type_pid')
            ->leftJoin('wh_stock_type tt','tt.id=g.type_id')
            ->leftJoin('wh_supplier ss','ss.id=g.supplier_id')
            ->where($map)
            ->where($map2)
            ->order('g.material_id desc,g.stock_sn desc,g.archives_sn asc')
            ->paginate()
            ->each(function ($v){

                //采购数量
                $v['num'] = Db::name('wh_material_goods')->where(['material_id'=>$v['material_id'],'stock_sn'=>$v['stock_sn']])->sum('num');
                $v['number'] = Db::name('wh_material_goods')->where(['material_id'=>$v['material_id'],'stock_sn'=>$v['stock_sn']])->sum('number');
                $v['num'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['num']}</div>";
                $v['number'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['number']}</div>";

                //收货情况
                $v['num2'] = Db::name('wh_stock_log')->where(['material_sn'=>$v['material_sn'],'stock_sn'=>$v['stock_sn']])->sum('num');
                $v['number2'] = Db::name('wh_stock_log')->where(['material_sn'=>$v['material_sn'],'stock_sn'=>$v['stock_sn']])->sum('number');
                $v['num2'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['num2']}</div>";
                $v['number2'] = "<div data-m-id='{$v['material_id']}{$v['stock_sn']}'>{$v['number2']}</div>";
                //面积表总数量
                $v['status_sum'] = Db::name('mill_order_archives')->where(['color'=>$v['archives_color']])->sum('number');
                //开料数量
                $give_where = [['g.order_id','=',$v['order_id']],['a.color','=',$v['archives_color']]];
                $v['status2_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->where([['g.status','>=',2]])
                    ->count('g.id');
                if($v['status2_sum'] == $v['status_sum'])$v['status2_sum'] = '<span class="label label-info">已完成</span>';
                else $v['status2_sum'] = '<span class="label label-danger">未完成</span>';
                //折弯数量
                $give_where = [['g.order_id','=',$v['order_id']],['a.color','=',$v['archives_color']]];
                $v['status3_sum'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($give_where)
                    ->where([['g.status','>=',3]])
                    ->count('g.id');
                if($v['status3_sum'] == $v['status_sum'])$v['status3_sum'] = '<span class="label label-info">已完成</span>';
                else $v['status3_sum'] = '<span class="label label-danger">未完成</span>';

                return $v;
            })
        ;

        //合计：库存，采购数量，采购重量，收货数量，收货重量
        //采购，库存去重求和：SUM(DISTINCT case when s.id then s.number else 0 end)
        $total = Db::name('wh_material_goods')
            ->alias('g')
            ->field('sum(g.num) as num,sum(g.number) as number,GROUP_CONCAT(DISTINCT s.id) as stock_ids')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('wh_stock s','s.stock_sn=g.stock_sn')
            ->where($map)
            ->where($map2)
            ->find();
        //收货
        $total1 = Db::name('wh_material_goods')
            ->alias('g')
            ->field('sum(g.num) as num,sum(g.number) as number')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($map)
            ->where($map2)
            ->where('g.status>=2')
            ->find();
        //库存
        $total2 = Db::name('wh_stock')
            ->field('sum(num) as num,sum(number) as number')
            ->where([['id','in',$total['stock_ids']],['number','>',0]])
            ->find();
        $total_str = "采购数量：{$total['num']}(次)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;采购重量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['num']}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货重量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['num']}(件)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp库存重量：{$total2['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";

        //搜索头
        $search_area = [
            ['select:2', 'g.supplier_id', '供应商', 'eq','',$supplier_list],
            ['text:1', 'g.model', '供应商色号', 'like'],
            ['text:1', 'o.engineering', '工程名称', 'like'],
            ['text:1', 'o.archives_sn', '档案号', 'like'],
            ['text:1', 'g.model', '规格型号', 'like'],
            ['text:1', 'g.lot_sn', '批号', 'like'],
            ['select:1', 'g.status', '收货状态', 'eq','',MaterialModel::$status],
            ['text:1', 'g.material_sn', '采购单号', 'like'],
            ['select:1', 'is_number', '有无库存', 'eq','',[1=>'无库存',2=>'有库存']],
            ['daterange:2', 'g.create_time', '采购日期'],
        ];

        $tab_js = '';
        //列表表头
        switch ($type_pid){
            //油漆库
            case in_array($type_pid,ColorModel::$type_pid_arr):
                unset($search_area[4]);
                unset($search_area[5]);
                unset($search_area[8]);

                $tab_column = [
                    // 批量添加列
                    'archives_bill_time'          =>  ['archives_bill_time', '下单日期','date','','','bg-color-1'],
                    'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                    'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                    'engineering'           =>  ['engineering', '工程名称','','','','bg-color-1'],
                    'archives_sn'           =>  ['archives_sn', '档案号','','','','bg-color-1'],
                    'batch'                 =>  ['batch', '批次','','','','bg-color-1'],
                    'archives_number'       =>  ['archives_number', '数量','','','','bg-color-1'],
                    'row_area'              =>  ['row_area', '面积(M²)','','','','bg-color-1'],
                    'material_name'         =>  ['material_name', '颜色名称'],
                    'supplier_color'        =>  ['supplier_color', '供应商色号'],
                    'color_sn'              =>  ['color_sn', '自编号'],
                    'color_type_id'         =>  ['color_type_id', '折弯类型',ColorModel::getColorType()],
                    'sum_number'            =>  ['sum_number', '库存(KG)'],
                    'supplier_name'         =>  ['supplier_name', '供应商'],
                    'number'                =>  ['number', '采购数量','','','','bg-color-2'],
                    'status'                =>  ['status', '收货状态',MaterialModel::$status,'','','bg-color-2'],
                    'number2'               =>  ['number2', '收货数量','','','','bg-color-2'],
                    'status2_sum'           =>  ['status2_sum', '开料情况','','','','bg-color-2'],
                    'status3_sum'           =>  ['status3_sum', '折弯情况','','','','bg-color-2'],
                ];
                $table_head_html = '<tr><th colspan="8">基本信息</th><th class="bg-color-2" colspan="6">颜色信息</th><th colspan="5">采购信息</th></tr>';

                $total_str = "采购数量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";

                $tab_js = '<script type="text/javascript">
                        //单元格合并
                        jQuery.fn.rowspan = function(colIdx=0) {
                            var that;
                            return this.each(function(row) {
                                $("td:eq(" + colIdx + ")", this).filter(":visible").each(function(col) {
                                    if (that != null && $(this).html() == $(that).html()) {
                                        rowspan = $(that).attr("rowSpan");
                                        if (rowspan == undefined) {
                                            $(that).attr("rowSpan", 1);
                                            rowspan = $(that).attr("rowSpan");
                                        }
                                        rowspan = Number(rowspan) + 1;
                                        $(that).attr("rowSpan", rowspan);
                                        $(this).hide();
                                    } else {
                                        that = this;
                                    }
                                });
                                
                            
                            });
                        };
                        $(function() {
                            //要合并的列序号，后面数字是第几列
                            $("#builder-table-main").find("tr").rowspan(14);
                            $("#builder-table-main").find("tr").rowspan(16);
                        });
                    </script>';

                break;
            //铝卷
            case 4:
                unset($search_area[1]);
                unset($search_area[2]);
                unset($search_area[3]);

                $tab_column = [
                    // 批量添加列
                    'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                    'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                    'material_name'         =>  ['material_name', '物料名称','','','','bg-color-1'],
                    'type_name'             =>  ['type_name', '系列(类别)','','','','bg-color-1'],
                    'supplier_name'         =>  ['supplier_name', '供应商','','','','bg-color-1'],
                    'model'                 =>  ['model', '规格型号','','','','bg-color-1'],
                    'quality'               =>  ['quality', '材质(合金状态)',ColorModel::getQuality(),'','','bg-color-1'],
                    'lot_sn'                =>  ['lot_sn', '批号','','','','bg-color-1'],
                    'sum_number'            =>  ['sum_number', '库存(M)','','','','bg-color-1'],
                    'number'                =>  ['number', '采购数量'],
                    'status'                =>  ['status', '收货状态',MaterialModel::$status],
                    'number2'               =>  ['number2', '收货数量'],
                ];
                $table_head_html = '<tr><th colspan="9">基本信息</th><th class="bg-color-2" colspan="3">采购信息</th></tr>';

                $total_str = "采购数量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";
                break;
            //铝板
            case 5:
                unset($search_area[1]);
                unset($search_area[2]);
                unset($search_area[3]);
                unset($search_area[5]);

                $tab_column = [
                    // 批量添加列
                    'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                    'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                    'material_name'         =>  ['material_name', '物料名称','','','','bg-color-1'],
                    'type_name'             =>  ['type_name', '厚度','','','','bg-color-1'],
                    'supplier_name'         =>  ['supplier_name', '供应商','','','','bg-color-1'],
                    'model'                 =>  ['model', '规格型号','','','','bg-color-1'],
                    //'quality'               =>  ['quality', '材质(合金状态)',ColorModel::getQuality(),'','','bg-color-1'],
                    //'lot_sn'                =>  ['lot_sn', '批号','','','','bg-color-1'],
                    'sum_number'            =>  ['sum_number', '库存数量(张)','','','','bg-color-1'],
                    'sum_num'               =>  ['sum_num', '库存重量(KG)','','','','bg-color-1'],
                    'num'                   =>  ['num', '采购数量(张)'],
                    'number'                =>  ['number', '采购重量(KG)'],
                    'status'                =>  ['status', '收货状态',MaterialModel::$status],
                    'number2'               =>  ['number2', '收货数量(张)'],
                    'num2'                  =>  ['num2', '收货重量(KG)'],
                ];
                $table_head_html = '<tr><th colspan="8">基本信息</th><th class="bg-color-2" colspan="5">采购信息</th></tr>';

                $total_str = "采购数量：{$total['num']}(张)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;采购重量：{$total['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货数量：{$total1['num']}(张)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;收货重量：{$total1['number']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库存数量：{$total2['number']}(张)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp库存重量：{$total2['num']}(KG)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp";
                break;
            //原材料
            case 3:
            //化工
            case 6:
                //其他
            case 7:
            default:
                unset($search_area[1]);
                unset($search_area[2]);
                unset($search_area[3]);
                unset($search_area[5]);

                $tab_column = [
                // 批量添加列
                'material_sn'           =>  ['material_sn', '采购单号','','','','bg-color-1'],
                'create_time'           =>  ['create_time', '采购日期','date','','','bg-color-1'],
                'material_name'         =>  ['material_name', '产品名称','','','','bg-color-1'],
                'supplier_name'         =>  ['supplier_name', '供应商','','','','bg-color-1'],
                //'long'                  =>  ['long', '长度(M)','','','','bg-color-1'],
                //'num'                   =>  ['num', '数量'],
                //'number'                =>  ['number', '重量(吨)'],
                'sum_num'               =>  ['sum_num', '库存数量(张)','','','','bg-color-1'],
                'sum_number'            =>  ['sum_number', '库存重量(KG)','','','','bg-color-1'],
                'create2_time'          =>  ['create_time2', '订单日期','date'],
                'num'                   =>  ['num', '采购数量(张)'],
                'number'                =>  ['number', '采购重量(KG)'],
                'status'                =>  ['status', '收货状态',MaterialModel::$status],
                'num2'                  =>  ['num2', '收货数量(张)'],
                'number2'               =>  ['number2', '收货重量(KG)'],
            ];
                $table_head_html = '<tr><th colspan="6">基本信息</th><th class="bg-color-2" colspan="6">采购信息</th></tr>';
                break;
        }

        $css = "<style>
                #builder-table > th,td{font-size: 12px;}
                .table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th {
                    padding: 8px;
                    font-size: 12px;
                    font-weight: 600;
                }
                .table-builder > tbody > tr > td {padding: 0 0 0 4px;}
                #builder-table-main {margin-bottom: -1px;}
                .table-builder, .table-bordered > thead > tr > .bg-color-1 {background: #fcca00;}
                .table-builder, .table-bordered > thead > tr > .bg-color-2 {background: #70b9eb;}
                .alert-dismissable{padding: initial;margin: inherit;}
            </style>";
        //JS
        $js = '
            <script type="text/javascript">
                $(function() {
                    $("#builder-table-wrapper").css("max-height","800px");
                    $("#builder-table-body").css("max-height","530px");
                    
                    var table_head_html = \''.$table_head_html.'\';
                    $("#builder-table-head table thead").html(table_head_html+$("#builder-table-head table thead").html());
                    $("#builder-table-right-head table thead").html(table_head_html+$("#builder-table-right-head table thead").html());
                    
                    //打印
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "采购单明细",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                    
                })
            </script>';
        $js .= $tab_js;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('采购单明细') // 页面标题
            ->setTableName('wh_material_goods') // 设置表名
            ->hideCheckbox()
            ->setPageTips($total_str,'info','topbtn')
            ->setTabNav($list_tab,empty($stock_type)?$type_pid:$stock_type)
            ->setSearchArea($search_area)
            ->addColumns($tab_column)
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn bg-info-light quality-print'])
            ->js('jquery.table2excel', 'common')
            ->setExtraCss($css)
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'batch'  => 60,
                'archives_number'  => 50,
                'color_type_id'     => 60,
                'number'     => 60,
                'status'     => 60,
                'number2'     => 60,
                'status2_sum'     => 74,
                'status3_sum'     => 74,
            ],80)
            ->fetch(); // 渲染模板
    }

    /**
     * 审核
     */
    public function backEnable()
    {

        $id = input('param.id');
        $fieldv = input('param.fieldv');
        $fieldv = explode('|',$fieldv);
        if (false === MaterialModel::where('id', $id)->setField($fieldv[0], $fieldv[1])) {
            $this->error('审核失败，订单ID：'.$id);
        }
        //审核人员
        MaterialModel::where('id', $id)->setField($fieldv[0].'_verify_uid', UID);
        //审核时间
        MaterialModel::where('id', $id)->setField($fieldv[0].'_time', time());

        Db::name('wh_material_goods')->where(['material_id'=>$id])->update(['status'=>1]);

        $this->success('提交成功', null, '_parent_reload');
    }

    /**
     * 审核不通过
     */
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === MaterialModel::where('id', $id)->setField($field, -1)) {
                $this->error('审核失败，订单ID：'.$id);
            }
            if(!empty($data[$field.'_note']))MaterialModel::where('id', $id)->setField($field.'_note', $data[$field.'_note']);
            //审核人员
            MaterialModel::where('id', $id)->setField($field.'_verify_uid', UID);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    /**
     * 导出采购单
     */
    public function showPrint(){

        $id = input('param.id');
        $print = input('print');

        $info = Db::name('wh_material')->where(['id'=>$id])->find();
        $info['is_order_color'] = $info['order_ids'];

        $type_pid = $info['type_pid'];

        if(!empty($info['order_ids']) && in_array($type_pid,ColorModel::$type_pid_arr)){
            if(!empty($order_ids))$info['order_ids'] = $order_ids;
            $info['order_color_ids'] = '';
            $info['lists'] = Db::name('mill_order')->where([['id','in',$info['order_ids']]])->select();
            foreach ($info['lists'] as &$v){
                //总面积
                $v['row_area'] = 0;
                $where = [
                    ['g.order_id','=',$v['id']],
                    ['g.material_id','=',$info['id']],
                ];
                $v['lists'] = Db::name('wh_material_goods')
                    ->alias('g')
                    ->field('g.*,o.archives_sn,o.engineering,s.title as supplier,st.title as type_name,ct.title as color_type_name')
                    ->leftJoin('mill_order o','g.order_id=o.id')
                    //->leftJoin('wh_order_color c','g.color_id=c.id')
                    ->leftJoin('wh_supplier s','g.supplier_id=s.id')
                    ->leftJoin('wh_stock_type st','g.type_id=st.id')
                    ->leftJoin('wh_supplier_color_type ct','g.color_type_id=ct.id')
                    ->where($where)
                    ->order('g.id asc')
                    ->select();
                foreach ($v['lists'] as &$vv){
                    //供应商
                    $v['supplier'] = $vv['supplier'];
                    $info['supplier_id'] = $vv['supplier_id'];
                    //总面积
                    $v['row_area'] += $vv['row_area'];
                    $info['row_area'] += $vv['row_area'];
                    //采购量
                    $info['number'] += $vv['number'];
                    //订单颜色ID
                    $info['order_color_ids'] .= ",{$vv['order_color_id']}";
                    //获取库存
                    $vv['sum_number'] = StockModel::getSumNumber($vv);
                };
            }
        }
        else {
            $info['lists'] = Db::name('wh_material_goods')->where([['material_id','=',$info['id']]])->select();
            foreach ($info['lists'] as &$v){
                //总面积
                if(empty($v['row_area']))$v['row_area'] = 0;
                //获取库存
                $v['sum_number'] = StockModel::getSumNumber($v);
                /*if($v['type_pid'] == 5){
                    $v['row_area2'] = $v['row_area'];
                    //理论重量
                    $v['kg'] = $v['long']*$v['high']*$v['row_area'];
                    //实际重量
                    $v['kg2'] = $v['long']*$v['high']*$v['row_area'];
                    //材质 order_id="+order_id+"&thickness="+
                    $type_text = floatval(Db::name('wh_stock_type')->where(['id'=>$v['type_id']])->value('title'));
                    $v['model_list'] = $this->getOrderArchives(['order_id'=>$v['order_id'],'thickness'=>$type_text,'re_type'=>1]);
                    foreach ($v['model_list'] as &$vv){
                        $vv['id'] = $vv['model'];
                        $vv['title'] = $vv['model'];
                        $vv['data_html'] = "data-row_area='{$vv['row_area']}'";
                    }
                }*/

            }
        }

        $info['stock_type'] = StockTypeModel::getGroup($type_pid);
        $info['supplier'] = SupplierModel::getGroup(0,$type_pid);
        $info['quality'] = ColorModel::getQuality($type_pid);
        $info['color_type'] = ColorModel::getColorType();
        $info['order'] = OrderModel::getList("CONCAT(engineering,' ',archives_sn,' ',batch)",['status'=>1]);
        $info['model_list'] = [];
        $info['order_color_ids'] = trim($info['order_color_ids'],',');

        $html = MaterialModel::toHtml($type_pid,$info,$print);

        if($print == 2)$html = str_replace('window.print();',"",$html);

        exit($html);
    }

    /**
     * 编辑厂家颜色
     */
    public function editColor(){

        $action = new Color();

        return $action->edit();
    }

    //根据厂家色号查找对应供应商
    public function supplierColorList(){

        $action = new Color();

        return $action->supplierColorList();
    }

    //根据厂家色号查找对应供应商
    public function getSupplier(){

        $action = new Color();

        return $action->getSupplier();
    }

    //AJAX类别列表
    public function getStockType(){

        $action = new Color();

        return $action->getStockType();
    }

}
